<template>
  <div class="search_container">
    <search-bar
      :value="keyword"
      @goSugs="goSugs"
    />
    <van-list
      :finished="finished"
      :offset="100"
      @load="onLoad"
      finished-text="没有更多了"
      v-model="loading"
    >
      <search-history
        @searchKeyWord="searchKeyWord"
        v-show="showHistory"
      />
      <search-sug
        @searchKeyWord="searchKeyWord"
        v-show="searchList.length === 0"
      />
      <search-list
        :searchList="searchList"
        v-show="searchList.length !== 0"
      />
    </van-list>
  </div>
</template>

<script>
import SearchBar from "./chi-coms/search-bar";
import SearchSug from "./chi-coms/search-sug";
import SearchHistory from "./chi-coms/search-history";
import SearchList from "./chi-coms/search-list";

import { getSearch } from "../../network/home";

export default {
  name: "Search",
  components: {
    SearchBar,
    SearchSug,
    SearchHistory,
    SearchList
  },
  computed: {
    showHistory() {
      if (this.searchList.length !== 0 || this.suggestionData.length !== 0) {
        return false;
      }
      return true;
    }
  },
  data() {
    return {
      suggestionData: [],
      searchList: [],
      finished: true,
      loading: false,
      keyword: "",
      page: 1,
      perPage: 20
    };
  },
  created() {
    this.$bus.$on("sendSearchData", res => {
      this.suggestionData = res.options;
    });
    this.$bus.$on("sendSearchList", _ => {
      this.searchList = [];
      this.keyword = "";
      this.finished = true;
      this.page = 1;
    });
  },
  methods: {
    searchKeyWord(value) {
      this.keyword = value;
      this.onLoad();
    },
    async onLoad() {
      if (this.keyword) {
        this.finished = false;
        // 1. 请求获取数据
        const result = await getSearch({
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.keyword // 搜索关键字
        });
        console.log(result);
        // 2. 将数据添加到列表中
        const { results } = result.data;
        this.searchList.push(...results);

        // 3. 设置加载状态结束
        this.loading = false;

        // 4. 判断数据是否加载完毕
        if (results.length) {
          this.page++; // 更新获取下一页数据的页码
        } else {
          this.finished = true; // 没有数据了，将加载状态设置结束，不再 onLoad
        }
      }
      return;
    },
    goSugs() {
      this.searchList = [];
      this.keyword = "";
      this.finished = true;
      this.page = 1;
    }
  }
};
</script>

<style scoped lang="stylus">
.van-list
  position fixed
  left 0
  right 0
  bottom 0
  top 46px
  overflow scroll
</style>